package com.md24housecall.fragment;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.md24housecall.activity.HomeActivity;
import com.md24housecall.activity.MainActivity;
import com.md24housecall.activity.R;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.manager.SkypeManager;
import com.md24housecall.model.User;
import com.md24housecall.net.ParsingUtils;
import com.md24housecall.net.UrlBuilder;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyConfig;
import com.md24housecall.util.MyLog;
import com.md24housecall.util.Utils;
import com.md24housecall.view.RatioImageView;
import com.md24housecall.view.RatioRelativeLayout;

public class HomeFragment extends Fragment {

	/*
	 * public interface OnCallCallback {
	 *//** When user enters correct code, and need switch to */
	/*
	 * public void onGotoChoosePeople(); }
	 */

	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	// private OnCallCallback mCallback;

	private int mTabPosition = 0;
	private AQuery aQuery;

	private Dialog mDlgCall;
	private ProgressDialog mProgressDialog;

	private RatioImageView mImgHeader;
	private RatioRelativeLayout mHeaderContainer;

	private ImageButton mDldBtnSubmitCode;
	private ImageButton mDldBtnGetCode;
	private EditText mDldEdtCode;
	private LinearLayout lnearCallSkype;

	// private boolean isCodeValid=false;
	private Utils util = Utils.getInstance();
	private String code = "";
//	private LinearLayout lnearCode;
	private GlobalConstant constant = GlobalConstant.getInstance();
	private OnClickListener sendCodeClick=null;
	protected View mainView;
	private Map<String, Object> paramGenerateCode=new HashMap<String, Object>();
	private int retry=0;
	private int retryGenerateCode=0;
	private RatioImageView btnCallNow,btnAverage,btnSatisfaction,btnIssueResolve;
	protected long startClick,endClick;
	private final int CLICK_DURATION=1500;

	public static HomeFragment newInstance(int tabPosition) {
		HomeFragment fragment = new HomeFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		/*
		 * try { mCallback = (OnCallCallback) activity; } catch
		 * (ClassCastException e) { throw new
		 * ClassCastException(activity.toString() +
		 * " must implement HelpFragment.OnCallCallback"); }
		 */
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	private void initialize(){
		aQuery = new AQuery(getActivity(), mainView);
		btnCallNow=(RatioImageView)mainView.findViewById(R.id.btn_callnow);
		btnCallNow.setRatio(DimenManager.WIDTH_BUTTON_IMG,DimenManager.HEIGHT_BUTTON_IMG);
		btnAverage=(RatioImageView)mainView.findViewById(R.id.btn_average);
		btnAverage.setRatio(DimenManager.WIDTH_BUTTON_IMG,DimenManager.HEIGHT_BUTTON_IMG);
		btnSatisfaction=(RatioImageView)mainView.findViewById(R.id.btn_satisfaction);
		btnSatisfaction.setRatio(DimenManager.WIDTH_BUTTON_IMG,DimenManager.HEIGHT_BUTTON_IMG);
		btnIssueResolve=(RatioImageView)mainView.findViewById(R.id.btn_issus_resolve);
		btnIssueResolve.setRatio(DimenManager.WIDTH_BUTTON_IMG,DimenManager.HEIGHT_BUTTON_IMG);
		mImgHeader = (RatioImageView) mainView.findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mHeaderContainer = (RatioRelativeLayout) mainView
				.findViewById(R.id.header_container);
		mHeaderContainer.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		code = util.getCode(getActivity());
		sendCodeClick=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!code.equals("")) {
					checkCode();
				} else {
					if (mDlgCall == null)
						createCallDialog();
					if (!mDlgCall.isShowing())
						mDlgCall.show();
				}
			}
		};
		AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
		builder.setMessage(getActivity().getResources().getString(R.string.msg_payment_for_call));
		builder.setPositiveButton(getActivity().getResources().getString(R.string.button_ok), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		createCallDialog();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (mDlgCall!=null && mDlgCall.isShowing())
			mDlgCall.dismiss();
		super.onDestroy();
	}
	private void addActions(){
		btnCallNow.setOnClickListener(sendCodeClick);
		if(mDlgCall!=null){
			mDlgCall.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					// TODO Auto-generated method stub
					MyLog.d(GlobalConstant.TAG, "cancel dialog");
					mDldEdtCode.setText("");
					code="";
					if(mDlgCall.isShowing())
						mDlgCall.cancel();
				}
			});
		}
//		mImgHeader.setOnClickListener(sendCodeClick);
	}
	protected View initView(LayoutInflater inflater,ViewGroup container){
		return inflater.inflate(R.layout.home, container, false);
	}
	
	protected void initLayout(){
		try{
			paramGenerateCode.put("email_address", util.getEmailAccount(getActivity()));
			MyLog.d(GlobalConstant.TAG, "email: "+util.getEmailAccount(getActivity()));
			if(SkypeManager.getInstance().getSkypename(getActivity())!=null || 
				!SkypeManager.getInstance().getSkypename(getActivity()).equals("")){
				paramGenerateCode.put("skype_name", SkypeManager.getInstance().getSkypename(getActivity()));
			}
			initialize();
			addActions();
		}catch (Exception e) {
			// TODO: handle exception
			MyLog.d(GlobalConstant.TAG, "exception onCreateView HomeFragment: "+ e.getMessage());
		}
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		endClick=System.currentTimeMillis();
		startClick=endClick;
		mainView=initView(inflater,container);
		initLayout();
		if(mainView.findViewById(R.id.txvBottom)!=null){
			if(MyConfig.DEBUG){
				((TextView)mainView.findViewById(R.id.txvBottom)).setText("BUILD FOR TEST");
			}
		}
		return mainView;
	}

	private void saveValidCode(String code){
		constant.isValidCode = true;
		util.saveCode(getActivity(), code);
		getActivity().finish();
		startActivity(new Intent(getActivity(),HomeActivity.class));
	}
	private void checkCode() {
		try{
			String url = UrlBuilder.buildWSAddUser(code);
			aQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
				@Override
				public void callback(String url, JSONObject object,AjaxStatus status) {
					constant.isValidCode = false;
					if (mProgressDialog != null && mProgressDialog.isShowing())
						mProgressDialog.dismiss();
					if(object==null){
						if(retry<3){
							retry++;
							checkCode();
						}else{
							MyLog.d(GlobalConstant.TAG, "no response from server");
							util.checkConnectionStatus(getActivity(), status,getString(R.string.dlg_call_code_get_error));
	//						if (mProgressDialog != null && mProgressDialog.isShowing())
	//							mProgressDialog.dismiss();
							retry=0;
						}
						return;
					}
					retry=0;
					if (status.getCode()==200) {
						MyLog.d(GlobalConstant.TAG, "json get code: "+object.toString());
						User user = ParsingUtils.parseUserManager(object);
						if (user.isUserEmpty()) {
							constant.isValidCode = false;
							Toast.makeText(getActivity(),R.string.dlg_call_code_invalid,Toast.LENGTH_LONG).show();
						} else {
							if (mDlgCall != null && mDlgCall.isShowing())
								mDlgCall.dismiss();
							//save user type
							util.savePreferenceInt(constant.KEYUSERTYPE, getActivity(), user.getType());
							util.savePreferenceString(constant.KEYUSERID, getActivity(), user.getId());
							
							//DucNM:load fragment request a call replace home fragment
							if(user.getUserCode()!=null && !user.getUserCode().equals(""))
								saveValidCode(user.getUserCode());
							else if(user.getCode()!=null && !user.getCode().equals(""))
								saveValidCode(user.getCode());
							//DucNM:load fragment request a call replace home fragment
							
							
						}
					} else {
						constant.isValidCode = false;
						util.checkConnectionStatus(getActivity(), status,getString(R.string.dlg_call_code_get_error));
	//					if (mProgressDialog != null && mProgressDialog.isShowing())
	//						mProgressDialog.dismiss();
					}
	
					if (mProgressDialog != null && mProgressDialog.isShowing())
						mProgressDialog.dismiss();
				}
			});
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private void createCallDialog() {
		mProgressDialog = new ProgressDialog(getActivity());
		mProgressDialog.setMessage(getResources().getString(
				R.string.str_loading));
		mProgressDialog.setCancelable(true);

		mDlgCall = new Dialog(getActivity());
		mDlgCall.requestWindowFeature(Window.FEATURE_NO_TITLE);

		mDlgCall.setContentView(R.layout.dialog_call);

		RatioImageView dlgMainBg = (RatioImageView) mDlgCall
				.findViewById(R.id.imgHeader);
		dlgMainBg.setRatio(DimenManager.WIDTH_DGL_ENTERCODE_HEADER_IMG,
				DimenManager.HEIGHT_DGL_ENTERCODE_HEADER_IMG);
		RatioRelativeLayout dlgHeaderContainer = (RatioRelativeLayout) mDlgCall
				.findViewById(R.id.header_container);
		dlgHeaderContainer.setRatio(
				DimenManager.WIDTH_DGL_ENTERCODE_HEADER_IMG,
				DimenManager.HEIGHT_DGL_ENTERCODE_HEADER_IMG);

		mDldBtnSubmitCode = (ImageButton) mDlgCall.findViewById(R.id.btnCall);
		mDldBtnGetCode = (ImageButton) mDlgCall.findViewById(R.id.btnGetCode);
		mDldEdtCode = (EditText) mDlgCall.findViewById(R.id.edtEnterCode);
		lnearCallSkype = (LinearLayout) mDlgCall
				.findViewById(R.id.lnearCallSkype);
//		lnearCode = (LinearLayout) mDlgCall.findViewById(R.id.lnearCode);
		if (code.equals("")) {
//			lnearCode.setVisibility(View.VISIBLE);
		} else {
			constant.isValidCode = true;
		}

		lnearCallSkype.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});

		mDldBtnSubmitCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				endClick=System.currentTimeMillis();
				if(endClick-startClick>=CLICK_DURATION){
					String inputCode = mDldEdtCode.getText().toString().trim();
					if (TextUtils.isEmpty(inputCode)) {
						Toast.makeText(getActivity(), R.string.dlg_call_no_code,Toast.LENGTH_SHORT).show();
						return;
					}
//					if (inputCode.length() < 4 || inputCode.length() > 6) {
//						Toast.makeText(getActivity(),R.string.dlg_call_code_length_error,Toast.LENGTH_SHORT).show();
//						return;
//					}
	
					InputMethodManager imm = (InputMethodManager) getActivity()
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(mDldEdtCode.getWindowToken(), 0);
					if(mProgressDialog!=null && !mProgressDialog.isShowing()){
						mProgressDialog.setMessage(getResources().getString(R.string.str_loading));
						mProgressDialog.show();
					}else{
						mProgressDialog.dismiss();
					}
					code = inputCode;
					startClick=endClick;
					checkCode();
					
				}
			}
		});

		mDldBtnGetCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				endClick=System.currentTimeMillis();
				if(endClick-startClick>=CLICK_DURATION){
					startClick=endClick;
					generateCode();
				}
			}
		});

		mDlgCall.setCanceledOnTouchOutside(false);
	}

	private void generateCode(){
		if(mProgressDialog!=null && !mProgressDialog.isShowing()){
			mProgressDialog.setMessage(getResources().getString(R.string.str_generating));
			mProgressDialog.show();
		}
		//generate code
		aQuery.ajax(UrlBuilder.URL_GENERATECODE,paramGenerateCode, JSONObject.class, new AjaxCallback<JSONObject>(){
			@Override
			public void callback(String url, JSONObject jsonObject,AjaxStatus status) {
				// TODO Auto-generated method stub
				if(jsonObject==null){
					MyLog.d(GlobalConstant.TAG, "no response generate code from server");
					if(retryGenerateCode<3){
						retryGenerateCode++;
						generateCode();
					}else{
						mDldBtnGetCode.setEnabled(true);
						util.checkConnectionStatus(getActivity(), status, getString(R.string.dlg_call_code_get_error));
						if (mProgressDialog != null && mProgressDialog.isShowing())
							mProgressDialog.dismiss();
						retryGenerateCode=0;
					}
					return;
				}
				mDldBtnGetCode.setEnabled(true);
				retryGenerateCode=0;
				if(mProgressDialog!=null && mProgressDialog.isShowing() && !getActivity().isFinishing())
					mProgressDialog.dismiss();
				MyLog.d(GlobalConstant.TAG, "home fragment: "+jsonObject.toString());
				try {
					String code=jsonObject.getString("code");
					MyLog.d(GlobalConstant.TAG,"code: "+code);
					if(!code.equals(""))
						saveValidCode(code);
					else{
						Toast.makeText(getActivity(), getResources().getString(R.string.dlg_generate_code_get_error), Toast.LENGTH_LONG).show();
					}
				}catch (Exception e) {
					// TODO: handle exception
					Toast.makeText(getActivity(), getResources().getString(R.string.dlg_generate_code_get_error), Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	public void hideCallDialog() {
		if (mDlgCall != null && mDlgCall.isShowing())
			mDlgCall.dismiss();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
}
